package com.api.demo.service.impl;

import com.api.demo.entity.User;
import com.api.demo.mapper.UserMapper;
import com.api.demo.service.UserService;
import com.api.demo.util.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public User register(User user) {
        // 检查用户名是否已存在
        if (findByUsername(user.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        // 设置默认角色
        if (user.getRole() == null) {
            user.setRole("USER");
        }

        // 保存用户
        save(user);
        return user;
    }

    @Override
    public String login(String username, String password) {
        try {
            System.out.println("开始登录，用户名：" + username);
            
            User user = findByUsername(username);
            if (user == null) {
                System.err.println("登录失败，用户不存在：" + username);
                throw new RuntimeException("用户不存在");
            }

            if (!passwordEncoder.matches(password, user.getPassword())) {
                System.err.println("登录失败，密码错误，用户名：" + username);
                throw new RuntimeException("密码错误");
            }

            // 生成JWT token
            String token = jwtUtil.generateToken(username, user.getId(), user.getRole());
            System.out.println("登录成功，用户名：" + username);
            return token;
        } catch (Exception e) {
            System.err.println("登录过程发生异常：" + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return getOne(queryWrapper);
    }
    
    @Override
    public boolean updateAvatar(Long userId, String avatarUrl) {
        try {
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", userId)
                    .set("avatar", avatarUrl)
                    .set("update_time", LocalDateTime.now());
            
            boolean result = update(updateWrapper);
            if (result) {
                System.out.println("用户头像更新成功，用户ID：" + userId);
            } else {
                System.out.println("用户头像更新失败，用户ID：" + userId);
            }
            return result;
        } catch (Exception e) {
            System.err.println("更新用户头像时发生异常，用户ID：" + userId + ", 错误: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("更新头像失败", e);
        }
    }
    
    @Override
    public User getById(Long id) {
        return super.getById(id);
    }
} 
